package com.ylkj.patient;

import static com.yilijk.base.utils.DevicesUtils.DEVICES_UUID;
import static com.yilijk.base.utils.DevicesUtils.getUUID;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import com.BV.LinearGradient.LinearGradientManager;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.baidu.mobstat.StatService;
import com.brentvatne.react.ReactVideoViewManager;
import com.examination.mlib.constants.ClickApi;
import com.examination.mlib.constants.PatientUrl;
import com.examination.mlib.constants.ProjectConfigure;
import com.examination.mlib.constants.UserInfoConstants;
import com.example.messagemodule.manager.TestImageLoader;
import com.google.gson.Gson;
import com.huawei.agconnect.common.network.AccessNetworkManager;
import com.huawei.agconnect.crash.AGConnectCrash;
import com.previewlibrary.ZoomMediaLoader;
import com.reactnativecommunity.viewpager.RNCViewPagerPackage;
import com.reactnativecommunity.viewpager.ReactViewPagerManager;
import com.reactnativecommunity.webview.RNCWebViewManager;
import com.reactnativecommunity.webview.RNCWebViewModule;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.users.rn.kit.RNKitManager;
import com.users.rn.rncommon.basic.RNReactModulesPackage;
import com.users.rn.rncommon.init.RNInitInterface;
import com.users.rn.rncommon.network.request.RequestListener;
import com.users.rn.rncommon.plugin.PluginInformation;
import com.examination.mlib.baseold.ModulesBaseApp;
import com.examination.mlib.interfaceapi.NetWorkCallBack;
import com.yilijk.base.AppBase;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.core.NetWorkService;
import com.yilijk.base.network.core.RetrofitManager;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.network.https.NetAttestationUtils;
import com.yilijk.base.network.https.interceptor.NetWorkUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.CommonUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;
import com.yilijk.base.utils.DevicesUtils;
import com.ylkj.patient.entity.RNHostBean;
import com.ylkj.patient.rnmodule.RNKitImModule;
import com.ylkj.patient.rnmodule.RNNetworkModule;
import com.ylkj.patient.rnmodule.RNRouterModule;
import com.ylkj.patient.utils.ThreeSDKInitUtils;
import com.ylkj.patient.utils.UmengUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.List;

import cn.qiuxiang.react.amap3d.AMapOfflineModule;
import cn.qiuxiang.react.amap3d.maps.AMapMarkerManager;
import cn.qiuxiang.react.amap3d.maps.AMapViewManager;
import me.jessyan.autosize.AutoSizeConfig;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//import com.example.imkefu.KefuImHelper;


public class MainApplication extends ModulesBaseApp {

    public static boolean homeType = true;  //true 代表 rn跳首页
    private static MainApplication mainApplication;
    public static int LocalDominNo = 3;
    String token = "";
    String mobile = "";

    public static IWXAPI iwxapi;

    public synchronized static MainApplication getMainApplication() {
//        if (mainApplication == null) {
//            mainApplication = new MainApplication();
//        }
        return mainApplication;
    }

    private boolean UserAgreeChecked = false;

    @Override
    public void onCreateModuleApp(Application application) {
        mainApplication = this;
        AppBase.init(application);
        AppBase.setEnable(BuildConfig.OPEN_LOG_OUT);
        LocalDominNo = BuildConfig.DOMIN_NO;


        if (SharedPreferencesUtils.getInstance().getUment_String("versionCode", "").trim().isEmpty()) {
            SharedPreferencesUtils.getInstance().removeAll();
            SharedPreferencesUtils.getInstance().removePop();
            SharedPreferencesUtils.getInstance().removeUmeng();
            SharedPreferencesUtils.getInstance().saveUment("versionCode", DevicesUtils.getVersionCode());
            SharedPreferencesUtils.getInstance().saveUment("versionName", DevicesUtils.getVersionName());
        } else {
            SharedPreferencesUtils.getInstance().saveUment("versionCode", DevicesUtils.getVersionCode());
            SharedPreferencesUtils.getInstance().saveUment("versionName", DevicesUtils.getVersionName());
        }

        token = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.token, null);
        mobile = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_mobile, null);

        initUUID();

        KitInit(this);
        WechatInit(this);
        ARouterInit(this);//ARouter9510222

        AutoSizeInit();//屏幕适配（今日头条）

        initUmeng();//Ument
        initThreeSDK();

//        CrashHandler.getInstance().init(this);
//        requestUrl();
//        KefuImHelper.getKefuImHelper().initKefu(this);


//        ClickUtils.sendEvent(ClickApi.App.app_onshow, this, "APP启动");

    }


    @Override
    public void onTerminate() {
        super.onTerminate();
        ClickUtils.sendEvent(ClickApi.App.app_onClose, this, "APP关闭");
    }

    //    @Override
//    public Resources getResources() {
//        Resources resources = super.getResources();
//        Configuration configuration = new Configuration();
//        configuration.setToDefaults();
//        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
//        return resources;
//    }

//    @Override
//    public void onConfigurationChanged(Configuration newConfig) {
//        if(newConfig.fontScale != 1){//非默认值
//        }
//        getResources();
//        super.onConfigurationChanged(newConfig);
//    }

//    @Override
//    public Resources getResources() {
//
//        Resources res = super.getResources();
//        if(res.getConfiguration().fontScale != 1){
//            Configuration newConfig = new Configuration();
//            newConfig.setToDefaults();//设置为默认值
//            res.updateConfiguration(newConfig,res.getDisplayMetrics());
//        }
//
//        return res;
//    }

    private void initUUID() {
        setUserAgreeChecked(false);
        if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(mobile)) {
            setUserAgreeChecked(true);
        }
        DEVICES_UUID = SharedPreferencesUtils.getInstance().getUment_String("sp_uuid", "");
        if (TextUtils.isEmpty(DEVICES_UUID)) {
            DEVICES_UUID = getUUID(this);
            NetAttestationUtils.getInstance().setSALT("");
            SharedPreferencesUtils.getInstance().saveUment("sp_uuid", DEVICES_UUID);
        }
    }

    public boolean isUserAgreeChecked() {
        return UserAgreeChecked;
    }

    public void setUserAgreeChecked(boolean userAgreeChecked) {
        UserAgreeChecked = userAgreeChecked;
//        if (userAgreeChecked) {
//            DEVICES_UUID = SharedPreferencesUtils.getInstance().getUment_String("sp_uuid", "");
//            if (TextUtils.isEmpty(DEVICES_UUID)) {
//                DEVICES_UUID = getUUID(this);
//                NetAttestationUtils.getInstance().setSALT("");
//                SharedPreferencesUtils.getInstance().saveUment("sp_uuid", DEVICES_UUID);
//            }
//        }
    }

    private void WechatInit(MainApplication mainApplication) {
        iwxapi = WXAPIFactory.createWXAPI(this, ProjectConfigure.WECHAT_ID);
        iwxapi.registerApp(ProjectConfigure.WECHAT_ID);
    }

    private void KitInit(MainApplication mainApplication) {
        RNReactModulesPackage.registerViewManager(ReactViewPagerManager.class);
        RNReactModulesPackage.registerViewManager(RNCWebViewManager.class);
        RNReactModulesPackage.registerNativeModule(RNCWebViewModule.class);
        RNReactModulesPackage.registerViewManager(LinearGradientManager.class);
        RNReactModulesPackage.registerViewManager(ReactVideoViewManager.class);
        RNReactModulesPackage.registerNativeModule(AMapOfflineModule.class);
        RNReactModulesPackage.registerViewManager(AMapMarkerManager.class);
        RNReactModulesPackage.registerViewManager(AMapViewManager.class);
        //react-native-scroll-ruler

//        RNReactModulesPackage.registerViewManager(SvgView.class);


//react-native-scroll-SVG


        RNKitManager.INSTANCE.kitInit(new RNInitInterface() {
            @Override
            public Application getContext() {
                return MainApplication.this;
            }

            @Override
            public String getDownloadUrl() {
                return "";
            }

            @Override
            public String getAppId() {
                return "2";
            }


            @Override
            public boolean isTestEnv() {
                return com.yilijk.base.utils.DevicesUtils.isEnvironment();
            }

            @Override
            public void requestPluginInfo(Context context, RequestListener<List<PluginInformation>> requestListener) {
                if (ProjectConfigure.Open.isRnUpdata) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("appid", 2);
                        jsonObject.put("version", 20000);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), jsonObject.toString());
                    Call<ResponseBody> call = RetrofitManager
                            .getRetrofitManager()
                            .getRetrofit()
                            .create(NetWorkService.class)
                            .post(DevicesUtils.isEnvironment() ? PatientUrl.ReactNativeZipUrl_t2 : PatientUrl.ReactNativeZipUrl, requestBody);
                    call.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            if (response != null && response.body() != null) {
                                if (!TextUtils.isEmpty(response.body().toString())) {
                                    try {
                                        String result = response.body().string();
                                        RNHostBean rnHostBean = new Gson().fromJson(result, RNHostBean.class);
                                        if (rnHostBean.getCode() == 200) {
                                            List<PluginInformation> data = rnHostBean.getData();
                                            requestListener.onSuccess(data);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {

                        }
                    });

//                    HttpUtils.post(DevicesUtils.isEnvironment() ? PatientUrl.ReactNativeZipUrl_test : PatientUrl.ReactNativeZipUrl, params, new HttpCallBack<RNHostBean>() {
//                        @Override
//                        public void onSuccess(RNHostBean rnHostBean, int i) {
//                            if (rnHostBean.getCode() == 200) {
//                                List<PluginInformation> data = rnHostBean.getData();
//                                requestListener.onSuccess(data);
//                            }
//                        }
//
//                        @Override
//                        public void onFailure(String s, int i) {
//
//                        }
//                    });

                }
            }
        });
        RNKitManager.INSTANCE.register(new RNRouterModule(), new RNNetworkModule(), new RNKitImModule());
    }


    private void initThreeSDK() {
        StatService.setAuthorizedState(this, false);
        ThreeSDKInitUtils.getInstance().setIsInitialized(false);
        if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(mobile)) {
            ALog.e("oakkk", "init three SDK Application!");
            ThreeSDKInitUtils.getInstance().init(this);
        }
    }


    //友盟
    private void initUmeng() {
        UmengUtils.setInitialized(false);
        UmengUtils.preInit(this);
        if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(mobile)) {
            UmengUtils.initUmeng(this, null);
        }

    }


    //屏幕适配
    private void AutoSizeInit() {
        //今日头条屏幕适配
        AutoSizeConfig.getInstance()
                .setDesignWidthInDp(375)
                .setDesignHeightInDp(863);
    }

    //Arouter
    private void ARouterInit(Application application) {
        if (BuildConfig.OPEN_LOG_OUT) {           // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog();     // 打印日志
            ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(application);
    }


}

